<!-- 分类管理 -->
<template>
  <div class="certificate-container flex-center">
    <div v-loading="treeLoading" class="left-content">
      <div class="tree-title">
        <span>分类管理</span>
        <px-select v-model="queryParams.classCode" style="width: 200px" placeholder="请选择科室" clearable @change="handleSelectChange">
          <px-option v-for="item in classNameList" :key="item.value" :label="item.name" :value="item.value" />
        </px-select>
        <px-tooltip content="新增" placement="top">
          <a v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION_ADD'" @click.stop="addNode({}, {}, 1)"> <TreeAdd class="tree-icon" /> </a>
        </px-tooltip>
      </div>
      <div class="tree-bar">
        <px-scrollbar>
          <px-tree
            ref="treeRef"
            :data="treeData"
            node-key="id"
            default-expand-all
            highlight-current
            :current-node-key="currentNode"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node show-hide">
                <span>
                  {{ data.name }}
                </span>
                <span class="tree-icon-container">
                  <span v-if="[1, 2].includes(node.level)">
                    <px-tooltip content="新增" placement="top">
                      <a v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION_ADD'" @click.stop="addNode(data, node)">
                        <TreeAdd class="tree-icon" />
                      </a>
                    </px-tooltip>
                  </span>
                  <!-- 一级菜单并且categoryType有值，不能编辑，其他的都能编辑 -->
                  <!-- v-if="!([1].includes(node.level) && node.data.categoryType)" -->
                  <span>
                    <px-tooltip content="编辑" placement="top">
                      <a v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION_EDIT'" @click.stop="editNode(data, node)">
                        <TreeEdit class="tree-icon" />
                      </a>
                    </px-tooltip>
                  </span>
                  <!-- 一级菜单并且categoryType有值，不能删除，其他的都能删除 -->
                  <!-- v-if="!([1].includes(node.level) && node.data.categoryType) || [2, 3].includes(node.level)" -->
                  <span>
                    <px-tooltip content="删除" placement="top">
                      <a v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION_DELETE'" @click.stop="deleteNode(data, node)">
                        <TreeDelete class="tree-icon" />
                      </a>
                    </px-tooltip>
                  </span>
                </span>
              </span>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
    </div>
    <div v-if="showContent" v-loading="loading" class="right-content">
      <div class="switch-bar flex-center">
        <span class="switch-title">消息提醒</span>
        <px-switch v-model="hasRemind" @change="changeRemind" />
        <div class="text-wrap">
          <px-icon class="filled-icon"><WarningFilled /></px-icon><span class="text">开启消息提醒，设置证照到期消息提醒</span>
        </div>
      </div>
      <div v-if="!hasRemind">消息提醒未开启</div>
      <div v-else class="right-content-form">
        <px-form ref="formRef" :model="formParams" :rules="rules" label-position="left" :validate-on-rule-change="false" label-width="100px">
          <div class="form-item-title">触发条件</div>
          <div class="form-item-wrap">
            <px-form-item label="站内消息" prop="triggerDuration" class="flex-center">
              <span class="text">有效日前</span>
              <px-input-number v-model="formParams.triggerDuration" placeholder="请输入" clearable class="mg-r-8" style="width: 400px" />
              <span class="text">天发送消息</span>
              <div class="text-wrap">
                <px-icon class="filled-icon"><WarningFilled /></px-icon><span class="text">临期、到期、过期状态的证照每日发送站内信提醒</span>
              </div>
            </px-form-item>
            <px-form-item label="邮件" prop="triggerDurationEmail" class="flex-center">
              <span class="text">有效日前</span>
              <px-input-number v-model="formParams.triggerDurationEmail" placeholder="请输入" clearable class="mg-r-8" style="width: 400px" />
              <span class="text">天发送消息</span>
              <div class="text-wrap">
                <px-icon class="filled-icon"><WarningFilled /></px-icon>
                <span class="text">临期状态的证照隔天发送邮件提醒，到期、过期状态的证照每日发送邮件提醒</span>
              </div>
            </px-form-item>
          </div>
          <div class="form-item-title">消息接收人</div>
          <div class="form-item-wrap mg-l78">
            <px-form-item label="用户" prop="users">
              <px-select
                v-model="formParams.users"
                placeholder="请选择"
                multiple
                filterable
                all-option
                clearable
                collapse-tags
                :max-collapse-tags="3"
                style="width: 400px"
              >
                <px-option v-for="item in personList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
            <px-form-item label="角色" prop="roles">
              <px-select
                v-model="formParams.roles"
                multiple
                clearable
                filterable
                all-option
                collapse-tags
                :max-collapse-tags="3"
                placeholder="请选择"
                style="width: 400px"
              >
                <px-option v-for="item in roleList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
            <px-form-item label="其他" prop="others">
              <px-select
                v-model="formParams.others"
                multiple
                clearable
                filterable
                all-option
                collapse-tags
                :max-collapse-tags="3"
                placeholder="请选择"
                style="width: 400px"
              >
                <px-option v-for="item in otherList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
            <px-form-item>
              <px-button @click="cancel">取消</px-button>
              <px-button v-has="'ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION_SAVE'" type="primary" @click="save">保存 & 更新下级</px-button>
            </px-form-item>
          </div>
        </px-form>
      </div>
    </div>
    <div v-if="!showContent" class="right-content">
      <div class="switch-bar flex-center">
        <span v-if="currentLevel === 3" class="switch-title">证照名称不支持单独设置消息提醒，请在上一层级设置。</span>
        <span v-if="currentLevel === 1" class="switch-title">一级分类暂不支持设置消息提醒，请选择二级分类进行设置</span>
      </div>
    </div>
    <!-- 新增/编辑 分类 -->
    <px-dialog v-model="treeDialogVisible" :title="treeFormTitle" width="400" @close="cancelTreeHandle">
      <px-form ref="treeFormRef" v-loading="formLoading" :model="treeFormParams" :rules="treeFormRules">
        <px-form-item label="分类名称" prop="classificationName" label-width="80">
          <px-input v-model="treeFormParams.classificationName" placeholder="请输入" clearable />
        </px-form-item>
        <px-form-item v-if="certificateTypeShow" label="证照类型" prop="certificateType" label-width="80">
          <px-select v-model="treeFormParams.certificateType" placeholder="请选择证照类型" clearable style="width: 100%">
            <px-option v-for="item in classificationList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="cancelTreeHandle">取消</px-button>
          <px-button type="primary" @click="saveTreeHandle">确定</px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed, watch, nextTick } from "vue";
import { getPersonListAPI, getRoleListAPI } from "@/api/knowledge/documentManage";
import TreeAdd from "@/assets/svg/knowledge/tree_add.svg?component";
import TreeEdit from "@/assets/svg/knowledge/tree_edit.svg?component";
import TreeDelete from "@/assets/svg/knowledge/tree_delete.svg?component";
import {
  getCertificateNoticeAPI,
  saveCertificateNoticeAPI,
  changeRemindStatusAPI,
  getTreeAPI,
  deleteTreeAPI,
  updateTreeAPI,
  setCreateTreeAPI
} from "@/api/knowledge/certificate";
import { PxMessage, PxMessageBox } from "px-ui";
import { queryCurrentClassList } from "@/api/common";

defineOptions({
  name: "ALL_KNOWLEDGE_CERTIFICATEMANAGE_CLASSIFICATION"
});

const treeRef = ref(null);
const formRef = ref(null);
const treeFormRef = ref(null);
const showContent = ref(false);

const state = reactive({
  treeLoading: false,
  loading: false,
  formLoading: false,
  hasRemind: false,
  formParams: {
    triggerDuration: 10,
    triggerDurationEmail: 10,
    users: [],
    roles: [],
    others: []
  },
  personList: [],
  roleList: [],
  otherList: [
    {
      name: "持证人",
      value: "holder"
    },
    {
      name: "创建人",
      value: "createByName"
    },
    {
      name: "更新人",
      value: "updateByName"
    }
  ],
  treeData: [],
  currentNode: 1,
  currentLevel: 1,
  treeDialogVisible: false,
  treeFormTitle: "",
  treeFormParams: {},
  messageConfigId: null,
  queryParams: {
    classCode: ""
  },
  currentNodeData: {},
  classificationList: [
    {
      value: "DEVICE",
      name: "设备类"
    },
    {
      value: "CERTIFICATE",
      name: "资格证类"
    }
  ],
  certificateTypeShow: true,
  classNameList: []
});
const {
  treeLoading,
  loading,
  formLoading,
  hasRemind,
  formParams,
  personList,
  roleList,
  otherList,
  treeData,
  currentNode,
  currentLevel,
  treeDialogVisible,
  treeFormTitle,
  treeFormParams,
  queryParams,
  classificationList,
  certificateTypeShow,
  classNameList
} = toRefs(state);

const rules = computed(() => ({
  triggerDuration: [{ required: true, message: "天数不能为空", trigger: "blur" }],
  triggerDurationEmail: [{ required: true, message: "天数不能为空", trigger: "blur" }]
}));

const treeFormRules = computed(() => ({
  classificationName: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  certificateType: [{ required: true, message: "证照类型不能为空", trigger: "blur" }]
}));

onMounted(() => {
  getPersonList();
  getRoleList();
  getClassNameSelect();
});

// 选择科室变化的事件
const handleSelectChange = () => {
  state.currentLevel = 1;
  state.currentNode = 1;
  state.currentNodeData = {};
  showContent.value = false;
  getTreeData();
};

// 获取科室数据
const getClassNameSelect = async () => {
  try {
    const res = await queryCurrentClassList();
    if (res?.length) {
      res?.forEach(i => {
        i.name = i.itemName;
      });
      res?.push({ value: "ERC", name: "HSE" });
      state.classNameList = res;
      state.queryParams.classCode = res?.[0]?.value || "";
      getTreeData();
    }
  } catch (error) {
    console.log(error);
  }
};

const getPersonList = async () => {
  state.personList = await getPersonListAPI();
  state.personList.forEach(item => {
    item.id = item.userId;
    item.name = `${item.username}-${item.realName}`;
    item.value = item.userId;
  });
};

const getRoleList = async () => {
  state.roleList = await getRoleListAPI();
  state.roleList.forEach(item => {
    item.id = item.roleId;
    item.name = item.roleName;
    item.value = item.roleId;
  });
};

const getTreeData = async () => {
  try {
    state.treeLoading = true;
    const params = {
      classCode: state.queryParams.classCode || ""
    };
    const res = await getTreeAPI(params);
    if (res?.length) {
      state.treeData = res;
      nextTick(() => {
        state.currentNode = res[0]?.id;
        treeRef.value?.setCurrentKey(res[0]?.id);
        getNoticeInfo(res[0]?.singleCode);
      });
    } else {
      state.treeData = [];
    }
  } catch (error) {
    console.log(error);
  } finally {
    state.treeLoading = false;
  }
};

// 点击树节点
const handleNodeClick = (data, node) => {
  console.log("data", data);
  console.log("node", node);
  if ([1, 3].includes(node?.level)) {
    showContent.value = false;
  } else {
    showContent.value = true;
  }
  state.currentLevel = node?.level;
  state.currentNode = data.id;
  nextTick(() => {
    treeRef.value?.setCurrentKey(data.id);
  });
  // 证照名称不调用信息配置接口，
  // treeLevel = 3 的都是证照名称
  if (data?.treeLevel !== 3) {
    getNoticeInfo(data.singleCode);
  }
  // 当前选中的节点
  state.currentNodeData = data;
};

// 新增分类
const addNode = (data, node, args) => {
  console.log("data", data);
  console.log("node", node);
  if ([1, 3].includes(node?.level)) {
    showContent.value = false;
  } else {
    if (args !== 1) {
      showContent.value = true;
    }
  }
  if (data.id) {
    state.currentNode = data.id;
    nextTick(() => {
      treeRef.value?.setCurrentKey(data.id);
    });
    // 证照名称不调用信息配置接口，
    // treeLevel = 3 的都是证照名称
    if (data?.treeLevel !== 3) {
      getNoticeInfo(data.singleCode);
    }
  }
  state.treeFormTitle = "新增分类";
  state.treeDialogVisible = true;
  state.treeFormParams.classificationName = "";
  // 当前选中的节点
  state.currentNodeData = data;
  if (args === 1) {
    state.certificateTypeShow = true;
  } else {
    state.certificateTypeShow = false;
  }
};

// 编辑分类
const editNode = (data, node, args) => {
  console.log("data", data);
  console.log("node", node);
  if ([1, 3].includes(node?.level)) {
    showContent.value = false;
  } else {
    showContent.value = true;
  }
  state.treeFormTitle = "编辑分类";
  state.treeDialogVisible = true;
  state.treeFormParams.classificationName = data.name;
  state.currentNode = data.id;
  nextTick(() => {
    treeRef.value?.setCurrentKey(data.id);
  });
  // 证照名称不调用信息配置接口，
  // treeLevel = 3 的都是证照名称
  if (data?.treeLevel !== 3) {
    getNoticeInfo(data.singleCode);
  }
  // 当前选中的节点
  state.currentNodeData = data;
  if (args === 1) {
    state.certificateTypeShow = true;
  } else {
    state.certificateTypeShow = false;
  }
};

// 删除
const deleteNode = (data, node) => {
  if ([1, 3].includes(node?.level)) {
    showContent.value = false;
  } else {
    showContent.value = true;
  }
  PxMessageBox.confirm("是否确定删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const res = await deleteTreeAPI(data.id);
      if (res) {
        PxMessage.success("删除成功");
        getTreeData();
      }
    } catch (error) {
      console.log(error);
    }
  });
};

// 保存分类
const saveTreeHandle = () => {
  treeFormRef.value.validate(async valid => {
    if (valid) {
      try {
        state.formLoading = true;
        // 新增:true,编辑:false
        let addOrEditBool = state.treeFormTitle.includes("新增") ? true : false;
        const { id, level, certificateType, parentSingleCode, singleCode } = state.currentNodeData;
        let classCode = state.queryParams.classCode;
        // 新增
        if (addOrEditBool) {
          const params = {
            level: state.certificateTypeShow ? 1 : level + 1,
            classCode: classCode,
            certificateType: state.certificateTypeShow ? state.treeFormParams.certificateType : certificateType,
            name: state.treeFormParams.classificationName,
            parentSingleCode: singleCode
          };
          const res = await setCreateTreeAPI(params);
          if (res) {
            PxMessage.success("新增成功");
            getTreeData();
          }
        } else {
          // 编辑
          const params = {
            id,
            level,
            classCode: classCode,
            certificateType: certificateType,
            name: state.treeFormParams.classificationName,
            parentSingleCode
          };
          const res = await updateTreeAPI(params);
          if (res) {
            PxMessage.success("编辑成功");
            getTreeData();
          }
        }
      } catch (error) {
        console.log(error);
      } finally {
        state.treeDialogVisible = false;
        state.formLoading = false;
        state.currentNodeData = {};
      }
    }
  });
};

const cancelTreeHandle = () => {
  treeFormRef.value.resetFields();
  state.treeDialogVisible = false;
};

const getNoticeInfo = async singleCode => {
  try {
    state.loading = true;
    const res = await getCertificateNoticeAPI({ certificateSingleCode: singleCode });
    if (res.messageConfigId) {
      state.formParams.triggerDuration = res.triggerDuration;
      state.formParams.triggerDurationEmail = res.triggerDurationEmail;
      state.formParams.users = res.account;
      state.formParams.roles = res.role;
      state.formParams.others = res.other;
      state.messageConfigId = res.messageConfigId;
    } else {
      state.formParams = {
        triggerDuration: 10,
        triggerDurationEmail: 10,
        users: [],
        roles: [],
        others: []
      };
      state.messageConfigId = null;
    }
    state.hasRemind = res.switchFlag === "on" ? true : false;
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 取消
const cancel = () => {
  formRef.value.resetFields();
};

// 保存
const save = async () => {
  if (state.formParams.users.length === 0 && state.formParams.roles.length === 0 && state.formParams.others.length === 0) {
    PxMessage.error("请至少选择一类消息接收人");
    return;
  }
  try {
    state.loading = true;
    const params = {
      messageConfigId: state.messageConfigId,
      certificateSingleCode: state.currentNodeData?.singleCode,
      triggerDuration: state.formParams.triggerDuration,
      triggerDurationEmail: state.formParams.triggerDurationEmail,
      account: state.formParams.users,
      role: state.formParams.roles,
      other: state.formParams.others,
      switchFlag: state.hasRemind ? "on" : "off"
    };
    const res = await saveCertificateNoticeAPI(params);
    PxMessage.success("保存成功");
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 切换提醒状态
const changeRemind = async val => {
  try {
    const params = {
      messageConfigId: state.messageConfigId,
      certificateSingleCode: state.currentNodeData?.singleCode,
      switchFlag: val ? "on" : "off"
    };
    state.loading = true;
    await changeRemindStatusAPI(params);
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/certificateManage/scss/common.scss");

.left-content {
  width: 316px;
  height: 100%;
  border: 1px solid #dfdfdf;
  border-radius: 4px;

  .tree-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px;
    font-size: 14px;
    font-weight: bold;
    border-bottom: 1px solid #dfdfdf;
  }

  .tree-search {
    padding: 8px;
  }

  .tree-bar {
    width: 100%;
    height: calc(100vh - 260px);
    overflow-y: auto;

    .tree-icon-container {
      box-sizing: border-box;

      .tree-icon {
        display: inline-block;
        margin: 8px 0 0 8px;
        font-size: 12px;
      }
    }

    :deep(.px-tree-node__content) {
      width: 315px;
    }

    .custom-tree-node {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: space-between;
      padding-right: 8px;
      font-size: 14px;
    }
  }
}

.right-content {
  width: calc(100% - 316px);
  height: 100%;
  padding-left: 18px;

  .right-content-form {
    display: flex;
    justify-content: center;
  }

  .switch-bar {
    margin-bottom: 16px;
  }

  .text-wrap {
    display: flex;
    align-items: center;
    margin-left: 5px;

    .text {
      font-size: 12px;
      font-weight: 300;
    }

    .filled-icon {
      margin-right: 2px;
      color: rgb(59 130 246);
    }
  }

  .switch-title {
    margin-right: 8px;
  }

  .form-item-title {
    margin-bottom: 8px;
    font-weight: bold;

    &::before {
      margin-right: 4px;
      color: red;
      content: "*";
    }
  }

  .form-item-wrap {
    margin-left: 70px;

    .text {
      margin-right: 10px;
      font-weight: 700;
      color: rgb(0 0 0 / 80%);
    }
  }

  .mg-l78 {
    margin-left: 78px;
  }
}
</style>
